//
//  SEGLoginRightView.m
//  Login
//
//  Created by 梁昆 on 16/8/16.
//  Copyright © 2016年 segiK. All rights reserved.
//
#import "SEGLoginRightView.h"
#import <Commom/UITextField+Limit.h>
#import <Commom/SEGSafaKeyboard.h>
#import <Commom/SEGPasswordTextField.h>

#define kUserPasswordStatus @"seg_PWDSTATUS"

@interface SEGLoginRightView () <UITextFieldDelegate, SGETextFieldLimitDelegate>
/**
 隐私政策
 */
@property (nonatomic, strong)SEGLabel *privacyLabel;
@end

@implementation SEGLoginRightView

- (instancetype)init
{
    if (self == [super init]) {
        self.backgroundColor = kColor_W;
        [self addSubview:self.headImageView];
        [self.headImageView mas_makeConstraints:^(MASConstraintMaker* make) {
            make.top.equalTo(self.mas_top).mas_offset(kStatusbarHeight+54);
            make.left.equalTo(self.mas_left).mas_offset(30);
            make.width.mas_equalTo(44);
            make.height.mas_equalTo(41);
        }];
        
        [self addSubview:self.titleLab];
        [self.titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.headImageView.mas_top);
            make.left.equalTo(self.headImageView.mas_right).mas_offset(7);
            make.height.mas_equalTo(23);
        }];
        
        [self addSubview:self.sloganLab];
        [self.sloganLab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.titleLab.mas_left);
            make.height.mas_equalTo(14);
            make.bottom.equalTo(self.headImageView.mas_bottom);
        }];
        
        [self addSubview:self.line1View];
        [self.line1View mas_makeConstraints:^(MASConstraintMaker* make) {
            make.top.equalTo(self.headImageView.mas_bottom).mas_offset(105);
            make.left.equalTo(self.headImageView.mas_left);
            make.right.equalTo(self.mas_right).mas_offset(-30);
            make.height.mas_equalTo(0.5);
        }];
        
        [self addSubview:self.line2View];
        [self.line2View mas_makeConstraints:^(MASConstraintMaker* make) {
            make.top.equalTo(self.line1View).mas_offset(60);
            make.left.right.equalTo(self.line1View);
            make.height.mas_equalTo(0.5);
        }];
        
        [self addSubview:self.phoneText];
        [self.phoneText mas_makeConstraints:^(MASConstraintMaker* make) {
            make.bottom.equalTo(self.line1View.mas_top);
            make.left.equalTo(self.line1View.mas_left);
            make.right.equalTo(self.line1View.mas_right).mas_offset(-30);
            make.height.mas_equalTo(17 + 34);
        }];
        
        [self addSubview:self.cleanPhoneButton];
        [self.cleanPhoneButton mas_makeConstraints:^(MASConstraintMaker* make) {
            make.bottom.equalTo(self.line1View.mas_top);
            make.right.equalTo(self.line1View.mas_right);
            make.width.mas_equalTo(30);
            make.height.equalTo(self.phoneText);
        }];
        
         //等保改造：去掉密码明暗文切换按钮
//        [self addSubview:self.seePasswordButton];
//        [self.seePasswordButton mas_makeConstraints:^(MASConstraintMaker *make) {
//            make.bottom.equalTo(self.line2View.mas_top);
//            make.right.equalTo(self.line2View.mas_right);
//            make.width.mas_equalTo(30);
//            make.height.equalTo(self.phoneText);
//        }];
        
        [self addSubview:self.passwordText];
        [self.passwordText mas_makeConstraints:^(MASConstraintMaker* make) {
            make.bottom.equalTo(self.line2View.mas_top);
            make.left.equalTo(self.line2View.mas_left);
            make.right.equalTo(self.line2View.mas_right).mas_offset(-30);
            make.height.mas_equalTo(17 + 34);
        }];
        
        [self addSubview:self.enterButton];
        [self.enterButton mas_makeConstraints:^(MASConstraintMaker* make) {
            make.top.equalTo(self.line2View.mas_bottom).mas_offset(55);
            make.left.right.equalTo(self.line1View);
            make.height.mas_equalTo(44);
        }];
        
        [self addSubview:self.losepassButton];
        [self.losepassButton mas_makeConstraints:^(MASConstraintMaker* make) {
            make.top.equalTo(self.enterButton.mas_bottom).mas_offset(5);
            make.left.equalTo(self.mas_left).mas_offset(122 * kScaleWidth);
            make.height.mas_equalTo(14+20);
            make.width.mas_equalTo(56);
        }];
        
        [self addSubview:self.verticalLine];
        [self.verticalLine mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self.mas_centerX);
            make.centerY.equalTo(self.losepassButton.mas_centerY);
            make.height.mas_equalTo(13);
            make.width.mas_equalTo(0.5);
        }];
        
        [self addSubview:self.gotoRegister];
        [self.gotoRegister mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.losepassButton.mas_top);
            make.right.equalTo(self.mas_right).mas_offset(-122 * kScaleWidth);
            make.height.equalTo(self.losepassButton.mas_height);
            make.width.equalTo(self.losepassButton.mas_width);
        }];
        
        //隐私政策
        [self addSubview:self.privacyLabel];
        [self.privacyLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(self);
            make.bottom.equalTo(self).offset(-30-LYSafeAreaBottom());
        }];
        
    }
    return self;
}

//设置手机号和密码
- (void)setPhoneText:(NSString *)phone passwordText:(NSString *)password
{
    self.phoneText.text = phone;
    self.passwordText.text = password;
    if (phone.length > 0 && password.length > 0) {
        self.enterButton.enabled = YES;
    } else {
        self.enterButton.enabled = NO;
    }
    // 等保取消明文显示
    // 改变密码明文/暗文显示
//    if ([[NSUserDefaults standardUserDefaults] boolForKey:kUserPasswordStatus]) {
//        self.seePasswordButton.selected = [[NSUserDefaults standardUserDefaults] boolForKey:kUserPasswordStatus];
//        self.passwordText.secureTextEntry = !self.seePasswordButton.selected;
//    }
    self.cleanPhoneButton.hidden = self.phoneText.text.length > 0 ? NO:YES;
}

#pragma mark - LoginDelegate
// 提示用户去注册
- (void)letGotoRegister {
    [self.loginDelegate GotoRegister];
}

//  忘记密码
- (void)losepassclick {
    [self.loginDelegate losePasswordWithPhoneNumber:self.phoneText.text];
}

//获取进入app 网络请求
- (void)enterButtonClick
{
    [self endEditing:YES];
    
    if (self.phoneText.text.length != 11) {
        [SEGAlertView showTmepMessageWithMessage:@"请输入正确的手机号码"];
    }
    else {
        NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:self.phoneText.text, @"tel", self.passwordText.text, @"password", nil];
        [self.loginDelegate enterLogin:dict];
    }
}
- (void)segSeePassword:(UIButton *)button {
    self.passwordText.secureTextEntry = button.isSelected;
    button.selected = !button.selected;
    // 记录明文/暗文 状态
    [[NSUserDefaults standardUserDefaults] setBool:button.selected forKey:kUserPasswordStatus];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark - 方法实现
//清空手机号
- (void)cleanPhoneText {
    self.phoneText.text = nil;
    self.cleanPhoneButton.hidden = YES;
    self.enterButton.enabled = NO;
}
//限制 phoneText 以及 passwordText 的UITextField输入长度
- (BOOL)textField:(UITextField*)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString*)string {
    
    if (self.phoneText.text.length > 0 && self.passwordText.text.length > 0) {
        self.enterButton.enabled = YES;
    } else {
        self.enterButton.enabled = NO;
    }
    
//    NSInteger existedLength = textField.text.length;
//    NSInteger selectedLength = range.length;
//    NSInteger replaceLength = string.length;
//    NSInteger length = existedLength - selectedLength + replaceLength;
//
//    if ([textField isEqual:self.phoneText]) {
//        // 不允许输入数字外的其他字符
//        NSString *checkedNumString = [string stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
//        if(checkedNumString.length > 0) return NO;
//        if (length > 11) return NO;
//
//        self.cleanPhoneButton.hidden = length > 0 ? NO:YES;
//        if (length > 0 && self.passwordText.text.length > 0) {
//            self.enterButton.enabled = YES;
//        } else {
//            self.enterButton.enabled = NO;
//        }
//
//    }
    
//    else if ([textField isEqual:self.passwordText]) {
//        if (self.phoneText.text.length > 0 && length > 0) {
//            self.enterButton.enabled = YES;
//        } else {
//            self.enterButton.enabled = NO;
//        }
//        // 解决退格变清空问题
//        if (range.length > 0 && string.length == 0)
//        {
//            //            [textField deleteBackward];
//            // Stores cursor position
//            UITextPosition *beginning = textField.beginningOfDocument;
//            UITextPosition *start = [textField positionFromPosition:beginning offset:range.location];
//            NSInteger cursorOffset = [textField offsetFromPosition:beginning toPosition:start] + string.length;
//            // Save the current text, in case iOS deletes the whole text
//            NSString *text = textField.text;
//            // Trigger deletion
//            [textField deleteBackward];
//            // iOS deleted the entire string
//            if (textField.text.length != text.length - 1)
//            {
//                textField.text = [text stringByReplacingCharactersInRange:range withString:string];
//                // Update cursor position
//                UITextPosition *newCursorPosition = [textField positionFromPosition:textField.beginningOfDocument offset:cursorOffset];
//                UITextRange *newSelectedRange = [textField textRangeFromPosition:newCursorPosition toPosition:newCursorPosition];
//                [textField setSelectedTextRange:newSelectedRange];
//            }
//            return NO;
//        }
//
//        // 解决再次编辑时内容被清空问题
//        NSString *updatedString = [textField.text stringByReplacingCharactersInRange:range withString:string];
//        textField.text = updatedString;
//        return NO;
//    }
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField*)textField {
    if (textField == self.passwordText && textField.text.length > 0) {
        [self enterButtonClick];
    }
    return YES;
}

#pragma mark - SGETextFieldLimitDelegate
- (void)limitTextFileDidChange:(UITextField *)textField {
    NSLog(@"🌧🌧 %s %@", __func__, textField);
    
    if (self.phoneText.text.length > 0 && self.passwordText.text.length > 0) {
       self.enterButton.enabled = YES;
    } else {
       self.enterButton.enabled = NO;
    }
    self.cleanPhoneButton.hidden = self.phoneText.text.length > 0 ? NO:YES;
}

#pragma mark -  getter  控件视图
//顶部图片
- (UIImageView*)headImageView
{
    if (!_headImageView) {
        _headImageView = [[UIImageView alloc] initWithImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_logo")]];
    }
    return _headImageView;
}
//第一根灰色分割线
- (UIView*)line1View
{
    if (!_line1View) {
        _line1View = [[UIView alloc] init];
        _line1View.backgroundColor = kColor_L2;
    }
    return _line1View;
}

- (UIView*)line2View
{
    if (!_line2View) {
        _line2View = [[UIView alloc] init];
        _line2View.backgroundColor = kColor_L2;
    }
    return _line2View;
}

//输入手机号码textfield
- (UITextField*)phoneText
{
    if (!_phoneText) {
        _phoneText = [[UITextField alloc] init];
        [_phoneText setTextColor:kColor_1];
        [_phoneText setFont:kFont_17];
        [_phoneText setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"请输入手机号" attributes:@{NSForegroundColorAttributeName:kColor_C}]];
        _phoneText.clearsOnBeginEditing = NO; //再次编辑不清空
        _phoneText.clearButtonMode = UITextFieldViewModeNever;
        [_phoneText configPhoneInputLimitWithDelegate:self];
        [_phoneText setTintColor:kColor_T];
    }
    return _phoneText;
}

//输入密码
- (SEGPasswordTextField*)passwordText
{
    if (!_passwordText) {
        _passwordText = [[SEGPasswordTextField alloc] init];
        [_passwordText setTextColor:kColor_1];
        [_passwordText setTintColor:kColor_T];
        [_passwordText setFont:kFont_17];
        [_passwordText setAttributedPlaceholder:[[NSAttributedString alloc] initWithString:@"请输入密码" attributes:@{NSForegroundColorAttributeName:kColor_C}]];
        _passwordText.secureTextEntry = YES;
        _passwordText.clearsOnBeginEditing = NO; //再次编辑不清空
        [_passwordText configPasswordInputLimitWithDelegate:self currentView:self];
//        _passwordText.delegate = self;
        _passwordText.limitDelegate = self;
    }
    return _passwordText;
}

//清空电话按钮
- (UIButton*)cleanPhoneButton
{
    if (!_cleanPhoneButton) {
        //发送验证码 按钮
        _cleanPhoneButton = [[UIButton alloc] init];
        [_cleanPhoneButton setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"icon_list_delete")] forState:UIControlStateNormal];
        [_cleanPhoneButton addTarget:self action:@selector(cleanPhoneText) forControlEvents:UIControlEventTouchUpInside];
        _cleanPhoneButton.hidden = YES;
    }
    return _cleanPhoneButton;
}

//“忘记密码”点击按钮
- (UIButton*)losepassButton
{
    if (!_losepassButton) {
        _losepassButton = [[UIButton alloc] init];
        [_losepassButton setTitle:@"忘记密码" forState:UIControlStateNormal];
        _losepassButton.titleLabel.font = kFont_13;
        [_losepassButton setTitleColor:[UIColor seg_setColorWithAny:kColor_1 dark:kColor_2] forState:UIControlStateNormal];
        [_losepassButton addTarget:self action:@selector(losepassclick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _losepassButton;
}

//“进入app”点击按钮
- (UIButton*)enterButton {
    if (!_enterButton) {
        _enterButton = [[UIButton alloc] init];
        _enterButton.backgroundColor = kColor_T;
        [_enterButton setBackgroundImage:[UIImage imageWithColor:kColor_T] forState:UIControlStateNormal];
        [_enterButton setBackgroundImage:[UIImage imageWithColor:kColor_T_Press] forState:UIControlStateHighlighted];
        [_enterButton setBackgroundImage:[UIImage imageWithColor:kColor_L2] forState:UIControlStateDisabled];
        [_enterButton setTitle:[NSString stringWithFormat:@"进入%@",kAppName] forState:UIControlStateNormal];
        _enterButton.titleLabel.font = kFont_16;
        // 进入按钮颜色特殊处理 高亮和暗黑的时候都是黑色
        [_enterButton setTitleColor:[UIColor colorWithHexString:@"#333333"] forState:UIControlStateNormal];
        [_enterButton setTitleColor:[UIColor seg_setColorWithAny:kColor_W dark:kColor_C] forState:UIControlStateDisabled];
        _enterButton.layer.masksToBounds = YES;
        _enterButton.layer.cornerRadius = 22;
        [_enterButton addTarget:self
                         action:@selector(enterButtonClick)
               forControlEvents:UIControlEventTouchUpInside];
        _enterButton.enabled = NO;
    }
    return _enterButton;
}

// 提示用户注册
- (UIButton*)gotoRegister
{
    if (!_gotoRegister) {
        _gotoRegister = [[UIButton alloc] init];
        [_gotoRegister setTitle:@"注册账号" forState:UIControlStateNormal];
        [_gotoRegister setTitleColor:[UIColor seg_setColorWithAny:kColor_1 dark:kColor_2] forState:UIControlStateNormal];
        _gotoRegister.titleLabel.font = kFont_13;
        _gotoRegister.tag = 1;
        [_gotoRegister addTarget:self action:@selector(letGotoRegister) forControlEvents:UIControlEventTouchUpInside];
    }
    return _gotoRegister;
}

//隐私政策
- (SEGLabel *)privacyLabel
{
    if (!_privacyLabel) {
        _privacyLabel = [[SEGLabel alloc] init];
        _privacyLabel.textAlignment = NSTextAlignmentCenter;
        NSString *str1 = @"登录即代表您已经同意";
        NSString *str2 = [NSString stringWithFormat:@"%@用户协议", kAppName];
        NSString *str3 = [NSString stringWithFormat:@"和隐私政策"];
        NSString *str = [NSString stringWithFormat:@"%@%@%@",str1,str2,str3];
        NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:str];
        text.yy_font = kFont_11;
        text.yy_color = kColor_3;
        //        text.yy_lineSpacing = 5;
        
        __weak typeof(self) weakSelf = self;
        //点击
        NSRange range = [str rangeOfString:@"隐私政策"];
        [text yy_setTextHighlightRange:range
                                 color:kColor_1
                       backgroundColor:[UIColor clearColor]
                             tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                                 if (weakSelf.loginDelegate && [weakSelf.loginDelegate respondsToSelector:@selector(gotoPrivacy)]) {
                                     [weakSelf.loginDelegate gotoPrivacy];
                                 }
                             }];
        NSRange range2 = [str rangeOfString:@"用户协议"];
        [text yy_setTextHighlightRange:range2
                                 color:kColor_1
                       backgroundColor:[UIColor clearColor]
                             tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                                 if (weakSelf.loginDelegate && [weakSelf.loginDelegate respondsToSelector:@selector(gotoUserAgreement)]) {
                                     [weakSelf.loginDelegate gotoUserAgreement];
                                 }
                             }];
        
        
        [text yy_setUnderlineStyle:NSUnderlineStyleSingle range:range];
        [text yy_setUnderlineStyle:NSUnderlineStyleSingle range:range2];
        _privacyLabel.attributedText = text;
    }
    return _privacyLabel;
}
- (UILabel *)titleLab {
    if (!_titleLab) {
        _titleLab = [[UILabel alloc] init];
        _titleLab.textColor = kColor_1;
        _titleLab.font = [UIFont boldSystemFontOfSize:21];
        _titleLab.text = @"欢迎来到";
    }
    return _titleLab;
}
- (UILabel *)sloganLab {
    if (!_sloganLab) {
        _sloganLab = [[UILabel alloc] init];
        _sloganLab.textColor = kColor_3;
        _sloganLab.font = kFont_13;
        _sloganLab.text = @"发现生活无限可能";
    }
    return _sloganLab;
}
//密码可视按钮
- (UIButton *)seePasswordButton {
    if (!_seePasswordButton) {
        //发送验证码 按钮
        _seePasswordButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_seePasswordButton setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_login_hide")]
                            forState:UIControlStateNormal];
        [_seePasswordButton setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"btn_login_show")]
                            forState:UIControlStateSelected];
        //[_seePasswordButton addTarget:self action:@selector(segSeePassword:) forControlEvents:UIControlEventTouchUpInside];
        _seePasswordButton.hidden = YES;
    }
    return _seePasswordButton;
}
- (UIView *)verticalLine {
    if (!_verticalLine) {
        _verticalLine = [[UIView alloc] init];
        _verticalLine.backgroundColor = kColor_L2;
    }
    return _verticalLine;
}

@end

